﻿using System;
using System.ServiceProcess;
using System.Threading;
using System.Windows.Forms;

namespace Sys.ServiceProcess
{
    public partial class ServiceControl : Form
    {
        public ServiceController Current { get; private set; }

        private Thread _tWait = null;

        public ServiceControl()
        {
            InitializeComponent();
        }

        public ServiceControl(string s)
        {
            InitializeComponent();

            Current = new ServiceController(s);

            _tWait = new Thread(new ParameterizedThreadStart(Wait));
        }

        public void Start()
        {
            if (Current.Status == ServiceControllerStatus.Stopped)
                Current.Start();


            lblMessage1.Text = "Windows is attempting start the following service on Local Computer...";
            lblMessage2.Text = Current.DisplayName;

            Show();

            _tWait.Start(ServiceControllerStatus.Running);
        }

        public void Stop()
        {
            if (Current.Status == ServiceControllerStatus.Running)
                Current.Stop();

            lblMessage1.Text = "Windows is attempting stop the following service on Local Computer...";
            lblMessage2.Text = Current.DisplayName;

            Show();

            _tWait.Start(ServiceControllerStatus.Stopped);            
        }

        private void OnClose(object sender, EventArgs e)
        {
            Close();
        }

        private void Wait(object status)
        {
            Current.WaitForStatus((ServiceControllerStatus)status);

            if (InvokeRequired)
                Invoke(new Action(Close));
        }
    }
}
